//
//  DetailViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14-10-9.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "WebViewController.h"
#import "OpenIdUtil.h"
#import "TakePhotoController.h"
#import <BaiduMapAPI/BMapKit.h>

@interface WebViewController () <UIWebViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

@property (retain, nonatomic) TakePhotoController * takephoto;
@property (retain, nonatomic) BMKLocationService * locService;
@property (retain, nonatomic) BMKGeoCodeSearch * geocodesearch;

@end

@implementation WebViewController
@synthesize webUrl,publicId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
            }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
     [self addTitleBarWithBackBtn:@"移动校园门户" needReturn:YES];
   
     if (publicId) {
        PublicAccount *pb = [PublicAccountDao queryForId:publicId];
        if (pb) {
            self.lableTitle.text = pb.appName;
        }
    }else{
        self.lableTitle.text = @"移动校园门户";

    }
   
    UIButton *coloseBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [coloseBtn setBackgroundImage:[[UIImage imageNamed:@"wallet_base_close_normal"]stretchableImageWithLeftCapWidth:10 topCapHeight:0] forState:UIControlStateNormal];
//  [coloseBtn setBackgroundImage:[[UIImage imageNamed:@"btntop_right_over_press"]stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateHighlighted];
//    [coloseBtn setTitle:@"关闭" forState:UIControlStateNormal];
//    coloseBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
//    [coloseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    coloseBtn.frame = CGRectMake(SCREEN_WIDTH-50, (YNEW)+2, 40.0f, 40.0f);
    [coloseBtn addTarget:self action:@selector(coloseBtn:) forControlEvents:UIControlEventTouchDown];
    [self.titlebar addSubview:coloseBtn];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_webView];
    _webView.delegate =self;
    
    _webView.scrollView.bounces = NO;
 
    //NSMutableURLRequest *request = [OpenIdUtil synCookies:webUrl publicId:publicId];
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"iOS_CSU", @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    
    NSURL *url = [NSURL URLWithString:webUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [_webView loadRequest:request];
}


-(void)btnBack
{
    if ([_webView canGoBack]) {
        [_webView goBack];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
       
    }
    
 }

-(void)coloseBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
- (BOOL)webView:(UIWebView *)WebView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlString = [[request URL] absoluteString];
    
    //NSLog(@" url1 = %@",urlString);

    if ([urlString containString:@"/connect/oauth2/authorize"] && ![urlString containString:@"REMARK="]) {
        NSString * stringReplace = [urlString stringByReplacingOccurrencesOfString:@"#wechat_redirect" withString:@""];
        NSString *strRemark =[NSString stringWithFormat:@"%@%@",@"&REMARK=",[OpenIdUtil createOpenId:DE.userId appId:publicId]];
        NSString *appendStr = [stringReplace stringByAppendingString:strRemark];
        //NSLog(@" url2 = %@",appendStr);
        NSURL *url = [NSURL URLWithString:appendStr];
        request = [NSMutableURLRequest requestWithURL:url];
        
        [self.webView loadRequest:request];
        //[WebView loadRequest:request];
        return YES;

    }
    
    NSArray *urlComps = [urlString componentsSeparatedByString:@":"];
    if([urlComps count] && [[urlComps objectAtIndex:0] isEqualToString:@"objc"])
    {
        
        NSString *funcStr = [urlComps objectAtIndex:1];
 
        if([funcStr isEqualToString:@"callLoaclPhoto"])
        {
            [self callLoaclPhoto];
        }
        else if ([funcStr isEqualToString:@"passChoosedAddress"]){
            if (urlComps.count>=4) {
                [self passChoosedAddress:[urlComps objectAtIndex:2] city:[urlComps objectAtIndex:3]];
            }
        }else if([funcStr isEqualToString:@"callTelApplication"]){
            
            if (urlComps.count>=3) {
                [self callTelApplication:[urlComps objectAtIndex:2]];
            }
        }
        
        else if([funcStr isEqualToString:@"showiOSProgress"]){
            
            [MBProgressHUD showHUDAddedTo:self.view prompt:@"加载中..." animated:YES];
        }
        else if([funcStr isEqualToString:@"closeiOSProgress"]){
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
        else if([funcStr isEqualToString:@"csuGetLocation"])
        {
            [self csuGetLocation];
        }
    }
    return YES;
}

//采集地理位置
-(void)csuGetLocation
{    
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
/**
 *	@brief	<#Description#>
 *
 *	@param 	userLocation 	<#userLocation description#>
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_locService stopUserLocationService];
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}


-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"csuGetLocationCallback('%f','%f','%@')",result.location.latitude,result.location.longitude, result.address]];
    [_locService stopUserLocationService];    
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error:%@", [error localizedDescription]);
    [_locService stopUserLocationService];
}


- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}


-(void)callTelApplication:(NSString*)tel{
   ;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: [NSString stringWithFormat:@"tel://%@",tel]]];
    
}
-(void)passChoosedAddress:(NSString*)proCode city:(NSString*)cityCode{
    
 
    [DE setGlobalVar:LOGIN_USER_PROV value:proCode];
    [DE setGlobalVar:LOGIN_USER_CITY value:cityCode];

}

//调用手机相册
-(void)callLoaclPhoto
{
    _takephoto = [TakePhotoController new];
    _takephoto.type = TakePhotoFromPhotoLibrary;
    _takephoto.isEdit = YES;
    __block WebViewController* webvi = self;
    _takephoto.blockComplete = ^(UIImage * image,NSDictionary*fileMap){
        
        [UploadFile uploadFileWithFilePath:[fileMap objectForKey:@"file"] servicePath:@"webview_app" params:fileMap calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
            
            if (success) {
                [DE setGlobalVar:LOGIN_USER_HEADIMG value:[netdata objectForKey:@"URL"]];
                NSString *urll = [netdata objectForKey:@"URL"];
                [webvi.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadImage('%@')",urll]];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:success?@"上传图片成功!":@"上传图片失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
        }];
        
    };
    
    [_takephoto startTakePhotoFromViewControl:self];
    
}

- (BOOL)canBecomeFirstResponder
{
    return YES;// default is NO
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"开始摇动手机");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"stop");
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"csuShakeCallback()"]];
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"取消");
}

@end
